//
//  PSTransaction.m
//  PSExtensions
//
//  Created by PoiSon on 15/10/15.
//  Copyright © 2015年 yerl. All rights reserved.
//

#import "PSTransaction.h"
#import "PSDicRecord_private.h"

@implementation PSTransaction{
    PSDbConfig *_config;
}
+ (instancetype)main{
    return [self new];
}

+ (instancetype)use:(NSString *)configName{
    return [[self alloc] initWithConfig:configName];
}

- (instancetype)init{
    PSDbConfig *config = [PSDbKit mainConfig];
    PSAssert(config, @"The main config is null, initialize PSDicRecord first");
    return self = [self initWithConfig:config.name];
}

- (instancetype)initWithConfig:(NSString *)configName{
    if (self = [super init]) {
        _config = [PSDbKit configForName:configName];
        PSAssert(_config, @"can't find config for name:%@", configName);
    }
    return self;
}

- (void)intercept:(NSInvocation *)invocation{
    PSDbConnection *conn = [_config getOpenedConnection];
    [_config setTransactionConnection:conn];
    [conn beginTransaction];
    @try {
        [invocation invoke];
        [conn commit];
    }
    @catch (NSException *exception) {
        [conn rollback];
        @throw exception;
    }
    @finally {
        [_config removeTransactionConnection];
        [_config close:conn];
    }
}
@end
